<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Announcement_Model extends CI_Model {
	
	public function count_announcement() {
		$query = "SELECT COUNT(*) AS sum FROM smb_announcements";
		$result = $this->db->query($query);
		if ($result->num_rows() == 1) {
			return $result->row()->sum;
		} else {
			$this->session->set_flashdata('error', 'Terjadi kesalahan saat akses database.');
			return NULL;
		}
	}
	
	public function get_announcement($offset, $limit) {
		$query = "SELECT * FROM smb_announcements ORDER BY date DESC LIMIT ?, ?";
		$result = $this->db->query($query, array(intval($offset), intval($limit)));
		if ($result->num_rows() > 0) {
			return $result->result();
		} else {
			$this->session->set_flashdata('error', 'Terjadi kesalahan saat akses database.');
			return NULL;
		}
	}
	
	public function get_announcement_by_id($id) {
		$query = "SELECT * FROM smb_announcements WHERE id = ?";
		$result = $this->db->query($query, array($id));
		if ($result->num_rows() != 1) {
			$this->session->set_flashdata('error', 'Terjadi kesalahan saat akses database.');
			return NULL;
		} else {
			return $result->row();
		}
	}
	
	public function add_announcement($creator, $title, $content) {
		$query = "INSERT INTO smb_announcements (id, creator, title, content) VALUES (UUID(), ?, ?, ?)";
		
		$this->db->trans_start();
		$this->db->query($query, array($creator, $title, $content));
		$this->db->trans_complete();
		
		if ($this->db->trans_status() === FALSE) {
			$this->session->set_flashdata('error', 'Terjadi kesalahan saat akses database.');
			return FALSE;
		} else {
			return TRUE;
		}
	}
	
	public function edit_announcement($id, $creator, $title, $content) {
		$query = "UPDATE smb_announcements SET creator = ?, title = ?, content = ?, date = CURRENT_TIMESTAMP WHERE id = ?";
		
		$this->db->trans_start();
		$this->db->query($query, array($creator, $title, $content, $id));
		$this->db->trans_complete();
		
		if ($this->db->trans_status() === FALSE) {
			$this->session->set_flashdata('error', 'Terjadi kesalahan saat akses database.');
			return FALSE;
		} else {
			return TRUE;
		}
	} 
	
	public function delete_announcement($id) {
		$query = "DELETE FROM smb_announcements WHERE id = ?";
		
		$this->db->trans_start();
		$this->db->query($query, array($id));
		$this->db->trans_complete();
		
		if ($this->db->trans_status() === FALSE) {
			$this->session->set_flashdata('error', 'Terjadi kesalahan saat akses database.');
			return FALSE;
		} else {
			return TRUE;
		}
	}
}